const express = require('express')
const router = express.Router()
const nodemailer = require("nodemailer")
const codeDB = require('../../db/regcode')
const tempPwDB = require('../../db/temppw')
const userDB = require('../../db/user')

// 发送验证码邮件
router.post('/getcode', async(req, res) => {
  let {user,email} = req.body
  let userReg = /^[^\s]{2,8}$/
  let regEmail = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
  if(user === ''){
    return res.send({
      code: 3,
      msg: '请先填写用户名'
    })
  }
  if(!userReg.test(user)){
    return res.send({
      code: 4,
      msg: '用户名格式不正确'
    })
  }
  if(email === ''){
    return res.send({
      code: 5,
      msg: '请先填写邮箱'
    })
  }
  if(!regEmail.test(email)){
    return res.send({
      code: 6,
      msg: '邮箱格式不正确'
    })
  }
  
  let userDoc
  userDoc = await userDB.findOne({user})
  if(userDoc){
    return res.send({
      code: 2,
      msg: '该用户名已注册'
    })
  }
  userDoc = await userDB.findOne({email})
  if(userDoc){
    return res.send({
      code: 2,
      msg: '该邮箱已注册'
    })
  }

  let codeDoc = await codeDB.findOne({email})
  if(codeDoc){
    let codeTime = Date.now() - codeDoc.date
    let oneMinute = 60 * 1000
    if(codeTime < oneMinute){
      return res.send({
        code: 7,
        msg: '验证码请求时间间隔为60秒'
      })
    }
  }
  
  let code = Math.floor(Math.random() * 9000) + 1000  
  // 创建发送邮件的对象
  let transporter = nodemailer.createTransport({
    host: "smtp.qq.com", // 发送方邮箱
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user: 'charlesxtd@foxmail.com', // 发送方邮箱地址
      pass: 'sxmbbzfhmxujbgif' // 授权码 这个有了才可以发送邮件，在163邮箱中看
    }
  })

  // 往数据库里存储验证码
  let doc = await codeDB.findOne({email})
  if(!doc){
    await codeDB.create({email, code})
  }else{
    await codeDB.findOneAndUpdate(email, {$set: {code, date:Date.now()}})
  }

  let option = {
    from: 'charlesxtd@foxmail.com', // sender address
    to: email, // list of receivers
    subject: "博客[無夢]注册验证码", // Subject line
    html: `<div style="background-color:#eef2fa;border:1px solid #d8e3e8;color: #111;padding:0 15px;-moz-border-radius:5px;-webkit-border-radius:5px;-khtml-border-radius:5px;">
           <p style="font-weight: bold;color: #2196F3;font-size: 18px;">验证码信息</p>
           <p>您好，<a href="mailto:${email}" rel="noopener" target="_blank">${email}</a></p>
           <p>您的验证码是${code}，有效期10分钟</p>
           </div>`
  }

  // 发送邮件
  transporter.sendMail(option, (err, data) => {
    if (err) {
      // console.log(err)
      res.send({
        code: 1,
        msg: err.response
      })
    } else {
      res.send({
        code: 0,
        msg: '邮件发送成功',
        data
      })
    }
  })
})

// 重设密码邮件
router.post('/retrievepw', async (req, res) => {
  let {user} = req.body
  let doc = await userDB.findOne({user})
  if(!doc){
    doc = await userDB.findOne({email: user})
  }
  if(!doc){
    return res.send({
      code: 1,
      msg: '该用户名或邮箱未在本站注册'
    })
  }

  user = doc.user
  let email = doc.email
  //let pw = Math.random().toString(36).substr(2) //临时密码

  // 创建一条临时数据，利用数据库的唯一_id作为验证
  let pwDoc = await tempPwDB.findOne({user})
  if(!pwDoc){
    pwDoc = await tempPwDB.create({user})
  }else{
    await tempPwDB
    .deleteOne({user})
    .catch(err=>{
            if(err) throw err
          })

    pwDoc = await tempPwDB.create({user})
  }
  let key = pwDoc._id

  let transporter = nodemailer.createTransport({
    host: "smtp.qq.com", // 发送方邮箱
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user: 'charlesxtd@foxmail.com', // 发送方邮箱地址
      pass: 'sxmbbzfhmxujbgif' // 授权码 这个有了才可以发送邮件，在163邮箱中看
    }
  })

  let option = {
    from: 'charlesxtd@foxmail.com', // sender address
    to: email, // list of receivers
    subject: "[無夢]密码重设", // Subject line
    html: `<div style="position:relative;font-size:14px;height:auto;padding:15px 15px 10px 15px;z-index:1;zoom:1;line-height:1.7;">
              有人要求重设如下帐号的密码：
              <br>
              <br>
              <a href='http://www.lessmore.cc/'>
              http://www.lessmore.cc/
              </a>
              <br>
              <br>
              用户名：${user}
              <br>
              <br>
              若这不是您本人要求的，请忽略本邮件，一切如常。
              <br>
              <br>
              要重置您的密码，请打开下面的链接：
              <br>
              <br>
              <a href='http://localhost:8080/retrieve-pw?action=rp&key=${key}&login=${user}' rel='noopener norefferrer' target="_blank">
                http://localhost:8080/retrieve-pw?action=rp&key=${key}&login=${user}
              </a>
          </div>`
  }

  transporter.sendMail(option, (err, data) => {
    if (err) {
      // console.log(err)
      res.send({
        code: 2,
        msg: err.response
      })
    } else {
      res.send({
        code: 0,
        msg: '邮件发送成功',
        data
      })
    }
  })
})

module.exports = router